<?php
// 应用公共文件
use app\common\util\OssUtil;

if (!function_exists('optPhoto')) {
    //图库选择
    function optPhoto($val, $name = '', $multiple = 0)
    {
        return '<button class="pear-btn pear-btn-primary pear-btn-sm" style="margin:4px 5px;vertical-align:top;" id="' . $val . '" type="button">图库选择</button>
       <script>
       layui.use(["jquery"],function() {
        let $ = layui.jquery;
        //弹出窗设置 自己设置弹出百分比
        function screen() {
            if (typeof width !== "number" || width === 0) {
            width = $(window).width() * 0.8;
            }
            if (typeof height !== "number" || height === 0) {
            height = $(window).height() - 20;
            }
            return [width + "px", height + "px"];
        }
        $("#' . $val . '").on("click", function () {
            layer.open({
                type: 2,
                maxmin: true,
                title: "图库选择",
                shade: 0.1,
                area: screen(),
                content:"/admin.php/index/optPhoto?name=' . $name . '&multiple=' . $multiple . '",
                success:function (layero,index) {
                    var iframe = window["layui-layer-iframe" + index];
                    iframe.child("' . $val . '")
                }
            });
        });
        })
        </script>';
    }
}

if (!function_exists('rm')) {
    //清除缓存
    function rm()
    {
        deleteDir(root_path() . 'runtime');
    }
}

if (!function_exists('isUrl')) {
    //是否
    function isUrl($url)
    {
        if (preg_match("/^http(s)?:\\/\\/.+/", $url)) return $url;
    }
}

if (!function_exists('randString')) {
    /**
     *  随机数
     *
     * @param string $length 长度
     * @param string $type 类型
     * @return void
     */
    function randString($length = '32', $type = 4): string
    {
        $rand = '';
        switch ($type) {
            case '1':
                $randstr = '0123456789';
                break;
            case '2':
                $randstr = 'abcdefghijklmnopqrstuvwxyz';
                break;
            case '3':
                $randstr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                break;
            default:
                $randstr = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                break;
        }
        $max = strlen($randstr) - 1;
        mt_srand((double)microtime() * 1000000);
        for ($i = 0; $i < $length; $i++) {
            $rand .= $randstr[mt_rand(0, $max)];
        }
        return $rand;
    }
}

if (!function_exists('setPassword')) {
    //密码截取
    function setPassword($password): string
    {
        return substr(md5($password), 3, -3);
    }
}

if (!function_exists('dataSign')) {
    /**
     * 数据签名认证
     */
    function dataSign($data = [])
    {
        if (!is_array($data)) {
            $data = (array)$data;
        }
        ksort($data);
        $code = http_build_query($data);
        $sign = sha1($code);
        return $sign;
    }
}

if (!function_exists('setWeb')) {
    /**
     * 修改网站配置文件
     */
    function setWeb($data = [])
    {
        $str = "<?php\r\n/**\r\n * 系统配置文件\r\n */\r\nreturn [\r\n";
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $str .= getArrTree($key, $value);
            } else {
                $str .= "\t'$key' => '$value',";
                $str .= "\r\n";
            }
        }
        $str .= '];';
        @file_put_contents(config_path() . 'web.php', $str);
    }
}

if (!function_exists('getImageSite')) {
    /**
     * 获取图片地址
     * @return mixed|string
     */
    function getImageSite()
    {
        global $globalConfig;
        if ($globalConfig['file_type'] == 3) {
            return $globalConfig['qiniu_pic_url'];
        } elseif ($globalConfig['file_type'] == 2) {
            return $globalConfig['file_pic_url'];
        } else {
            return config('app.app_host');
        }
    }
}

if (!function_exists('dealImage')) {
    /**
     * 图片前缀处理
     * @param $image string|array 图片
     * @param int $mode 1：提取 0：保存
     * @param string|array $field 修改的字段
     * @param int $type 1 单图，0 多图
     * @return array|string
     */
    function dealImage($image, int $mode = 1, $field = ['image'], int $type = 1)
    {
        $domin = getImageSite();
        if ($mode) {
            if ($type == 1) {
                //本身是网址
                if (isUrl($image)) {
                    $data = $image;
                } else {
                    $data = $image ? $domin . str_replace('\\', '/', $image) : '';
                }
            } else {
                $data = [];
                if ($image) {
                    foreach ($image as $item) {
                        if ($field) {
                            foreach ($field as $value) {
                                if (!isUrl($item[$value])) {
                                    $item[$value] = $item[$value] ? $domin . str_replace('\\', '/', $item[$value]) : '';
                                }
                            }
                        } else {
                            if (!isUrl($item)) {
                                $item = $item ? $domin . str_replace('\\', '/', $item) : '';
                            }
                        }
                        $data[] = $item;
                    }
                }
            }
            return $data;
        } else {
            return str_replace(getImageSite(), '', $image);
        }
    }
}

if (!function_exists('getArrTree')) {
    /**
     * 递归配置数组
     */
    function getArrTree($key, $data, $level = "\t")
    {
        $i = "$level'$key' => [\r\n";
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $i .= getArrTree($k, $v, $level . "\t");
            } else {
                $i .= "$level\t'$k' => '$v',";
                $i .= "\r\n";
            }
        }
        return $i . "$level" . '],' . "\r\n";
    }
}

if (!function_exists('aesEncrypt')) {
    /**
     *
     * @param string $string 需要加密的字符串
     * @param string $key 密钥
     * @return string
     */
    function aesEncrypt($string, $key = "ONSPEED"): string
    {
        $data = openssl_encrypt($string, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        return strtolower(bin2hex($data));
    }
}

if (!function_exists('aesDecrypt')) {
    /**
     * @param string $string 需要解密的字符串
     * @param string $key 密钥
     * @return string
     */
    function aesDecrypt($string, $key = "ONSPEED"): string
    {
        try {
            return openssl_decrypt(hex2bin($string), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        } catch (\Exception $e) {
            return false;
        }
    }
}

if (!function_exists('authCode')) {
    /**
     * 加密解密函数
     * @param string $string 加密解密字符串
     * @param string $operation ENCODE DECODE
     * @param string $key 别外key
     * @param int $expiry 过期时间
     * @return string
     */
    function authCode($string, $operation = 'DECODE', $key = '', $expiry = 0)
    {

        $ckey_length = 4; // 随机密钥长度 取值 0-32;
        // 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
        // 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
        // 当此值为 0 时，则不产生随机密钥

        $key = md5($key ? $key : 'NULL');
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);

        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);

        $result = '';
        $box = range(0, 255);

        $rndkey = array();
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }

        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }

        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }

        if ($operation == 'DECODE') {
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            return $keyc . str_replace('=', '', base64_encode($result));
        }
    }
}

if (!function_exists('getField')) {
    /**
     * 获取指定表指定行指定字段
     * @param string $tn 完整表名
     * @param string|array $where 参数数组或者id值
     * @param string $field 字段名,默认'name'
     * @param string $default 获取失败的默认值,默认''
     * @param array $order 排序数组
     * @return string                获取到的内容
     */
    function getField($tn, $where, $field = 'name', $default = '', $order = ['id' => 'desc'])
    {
        if (!is_array($where)) {
            $where = ['id' => $where];
        }
        $row = \think\facade\Db::name($tn)->field([$field])->where($where)->order($order)->find();
        return $row === null ? $default : $row[$field];
    }
}

if (!function_exists('deleteDir')) {
    /**
     * 遍历删除文件夹所有内容
     * @param string $dir 要删除的文件夹
     */
    function deleteDir($dir)
    {
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != '.' && $file != '..') {
                $filepath = $dir . '/' . $file;
                if (is_dir($filepath)) {
                    deleteDir($filepath);
                } else {
                    @unlink($filepath);
                }
            }
        }
        closedir($dh);
        @rmdir($dir);
    }
}

if (!function_exists('getTree')) {
    /**
     * 递归无限级分类权限
     * @param array $data
     * @param int $pid
     * @param string $field1 父级字段
     * @param string $field2 子级关联的父级字段
     * @param string $field3 子级键值
     * @return mixed
     */
    function getTree($data, $pid = 0, $field1 = 'id', $field2 = 'pid', $field3 = 'children')
    {
        $arr = [];
        foreach ($data as $k => $v) {
            if ($v[$field2] == $pid) {
                $v[$field3] = getTree($data, $v[$field1]);
                $arr[] = $v;
            }
        }
        return $arr;
    }
}

if (!function_exists('humpUnderline')) {
    /**
     * 驼峰转下划线
     * @param string $str 需要转换的字符串
     * @return string      转换完毕的字符串
     */
    function humpUnderline($str)
    {
        return strtolower(trim(preg_replace('/[A-Z]/', '_\\0', $str), '_'));
    }
}

if (!function_exists('underlineHump')) {
    /**
     * 下划线转驼峰
     * @param string $str 需要转换的字符串
     * @return string      转换完毕的字符串
     */
    function underlineHump($str)
    {
        return ucfirst(
            preg_replace_callback('/_([a-zA-Z])/', function ($match) {
                return strtoupper($match[1]);
            }, $str)
        );
    }
}

if (!function_exists('recordLog')) {
    /**
     * @记录日志
     * @param [type] $param
     * @param string $file
     *
     * @return void
     */
    function recordLog($param, $file = '')
    {
        $path = root_path() . 'log/' . $file . "/";
        if (!is_dir($path)) @mkdir($path, 0777, true);
        if (is_array($param)) {
            $param = json_encode($param, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);
        }
        @file_put_contents(
            $path . date("Y_m_d", time()) . ".txt",
            "执行日期：" . "\r\n" . date('Y-m-d H:i:s', time()) . ' ' . "\n" . $param . "\r\n",
            FILE_APPEND
        );
    }

}

if (!function_exists('isXml')) {
    /**
     * 判断是否为xml格式
     * @param $string
     * @return false|mixed
     */
    function isXml($string)
    {
        $xml_parser = xml_parser_create();
        if (!xml_parse($xml_parser, $string, true)) {
            xml_parser_free($xml_parser);
            return false;
        } else {
            return (json_decode(json_encode(simplexml_load_string($string)), true));
        }
    }
}

if (!function_exists('xmlToArray')) {
    /**
     * xml转array
     * @param $string
     * @return mixed
     */
    function xmlToArray($string)
    {
        if (isXml($string)) {
            $str = simplexml_load_string($string);
            return json_decode($str, true);
        } else {
            return $string;
        }
    }
}

if (!function_exists('checkMobile')) {
    /**
     * 检查手机号
     * @param $mobile
     * @return bool
     */
    function checkMobile($mobile)
    {
        $isMob = "/^1[3456789]\d{9}/";
        $isTel2 = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        $res = preg_match($isMob, $mobile) || preg_match($isTel2, $mobile);
        return (bool)$res;
    }
}

if (!function_exists('checkEmail')) {
    /**
     * 检查邮箱
     * @param $email
     * @return bool
     */
    function checkEmail($email): bool
    {
        $isValid = preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,14}$/', $email);
        return (bool)$isValid;
    }
}

if (!function_exists('imageToThumb')) {
    /**
     * 图片修改尺寸
     * @param $url string 地址
     * @param $width int 宽
     * @param $height int 高
     * @param $mime string 图片格式
     * @return array
     */
    function imageToThumb($url, $width, $height, $mime)
    {
        $sizeM = (((int)(strlen(file_get_contents($url)) / 1024 / 1024)) ?: 1) * 2;
        $newImage = imagecreatetruecolor($width / $sizeM, $height / $sizeM);
        $source = $mime == 'image/jpeg' ? imagecreatefromjpeg($url) : imagecreatefrompng($url);
        imagecopyresized($newImage, $source, 0, 0, 0, 0, $width / $sizeM, $height / $sizeM, $width, $height);
        $path = '/upload/default/' . date('Ymd') . '/' . md5($url) . ($mime == 'image/jpeg' ? '.jpg' : '.png');
        $mime == 'image/jpeg' ? imagejpeg($newImage, root_path() . 'public/' . $path) : imagepng($newImage, root_path() . 'public/' . $path);
        imagedestroy($newImage);
        return [$path, $width / $sizeM, $height / $sizeM];
    }
}

if (!function_exists('downloadFile')) {
    /**
     * @param $url
     * @return string
     */
    function downloadFile($url)
    {
        $arr = explode('/', $url);
        $name = $arr[count($arr) - 1];
        $fileName = root_path() . '/public/upload/download/' . date('Ymd');
        if (!file_exists($fileName)) mkdir($fileName, 0777, true);
        $imageData = file_get_contents($url);
        $file = fopen($fileName . '/' . $name, 'w');
        fwrite($file, $imageData);
        fclose($file);
        return $fileName . '/' . $name;
    }
}

if (!function_exists('delUploadFile')) {
    /**
     * 删除本地文件
     * @param $path
     */
    function delUploadFile($path)
    {
        unlink($path);
    }
}

if (!function_exists('createQrcode')) {
    /**
     * 生成二维码图片
     * @param string $string
     * @param string $rename
     */
    function createQrcode($string, $rename, $encrypt = false)
    {
        require_once root_path() . 'extend/qrcode/phpqrcode.php';
        $string = $encrypt ? aesEncrypt($string) : $string;
        $errorCorrectionLevel = 'H';//容错级别
        $matrixPointSize = 20;//生成图片大小
        $dir = root_path() . '/public/upload/qrcode';
        if (!is_dir($dir)) {
            // 创建文件加
            mkdir($dir);
        }
        $QR = $dir . '/' . $rename . '.png';
        QRcode::png($string, $QR, $errorCorrectionLevel, $matrixPointSize, 1);
        $logo = root_path() . '/public/upload/qrcode_logo.jpg';//准备好的logo图片
        if (file_exists($logo)) {
            $QR = imagecreatefromstring(file_get_contents($QR));
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR);//二维码图片宽度
            $QR_height = imagesy($QR);//二维码图片高度
            $logo_width = imagesx($logo);//logo图片宽度
            $logo_height = imagesy($logo);//logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                $logo_qr_height, $logo_width, $logo_height);
            imagepng($QR, $dir . '/' . $rename . '.png');
        }
        return dealImage('/upload/qrcode/' . $rename . '.png');
    }
}

if (!function_exists('bubblingSort')) {
    /**
     * 二分排序
     * @param $list
     * @param string $field
     * @param string $sort
     * @return array|mixed
     */
    function bubblingSort($list, $field = 'weight', $sort = 'desc')
    {
        $len = count($list);
        for ($i = 0; $i < $len - 1; $i++) {
            for ($j = 0; $j < $len - $i - 1; $j++) {
                if ($sort == 'desc') {
                    if ($list[$j][$field] < $list[$j + 1][$field]) {
                        $tmp = $list[$j];
                        $list[$j] = $list[$j + 1];
                        $list[$j + 1] = $tmp;
                    }
                } else {
                    if ($list[$j][$field] > $list[$j + 1][$field]) {
                        $tmp = $list[$j];
                        $list[$j] = $list[$j + 1];
                        $list[$j + 1] = $tmp;
                    }
                }
            }
        }
        return $list;
    }
}

if (!function_exists('numToCN')) {
    /**
     * 数字转文字
     * @param $num
     * @param int $type 0:RMB 1:text
     * @return false|string
     */
    function numToCN($num, $type = 0)
    {
        $c1 = "零壹贰叁肆伍陆柒捌玖";
        $c2 = "分角元拾佰仟万拾佰仟亿";
        if ($type) {
            $c1 = "零一二三四五六七八九";
            $c2 = "分角元十百千万十百千亿";
        }
        //精确到分后面就不要了，所以只留两个小数位
        $num = round($num, 2);
        //将数字转化为整数
        $num = $num * 100;
        if (strlen($num) > 10) {
            return "数字太大，请检查";
        }
        $i = 0;
        $c = "";
        while (1) {
            if ($i == 0) {
                //获取最后一位数字
                $n = substr($num, strlen($num) - 1, 1);
            } else {
                $n = $num % 10;
            }    //每次将最后一位数字转化为中文
            $p1 = substr($c1, 3 * $n, 3);
            $p2 = substr($c2, 3 * $i, 3);
            if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
                $c = $p1 . $p2 . $c;
            } else {
                $c = $p1 . $c;
            }
            $i = $i + 1;
            //去掉数字最后一位了
            $num = $num / 10;
            $num = (int)$num;
            //结束循环
            if ($num == 0) {
                break;
            }
        }
        $j = 0;
        $slen = strlen($c);
        while ($j < $slen) {
            //utf8一个汉字相当3个字符
            $m = substr($c, $j, 6);
            //处理数字中很多0的情况,每次循环去掉一个汉字“零”
            if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
                $left = substr($c, 0, $j);
                $right = substr($c, $j + 3);
                $c = $left . $right;
                $j = $j - 3;
                $slen = $slen - 3;
            }
            $j = $j + 3;
        }
        //这个是为了去掉类似23.0中最后一个“零”字
        if (substr($c, strlen($c) - 3, 3) == '零') {
            $c = substr($c, 0, strlen($c) - 3);
            if ($type) {
                $c = str_replace('元', '', $c);
                $c = str_replace('整', '', $c);
            }
            return $c;
        } else {
            return $c;
        }
    }
}

if (!function_exists('apiReturn')) {
    /**
     * ajax返回操作
     * @param $code
     * @param string $msg
     * @param array $returnData
     * @param array $extend
     */
    function apiReturn($code, $msg = '', $returnData = [], $extend = [])
    {
        if ($extend) {
            $data = array(
                'code' => $code,
                'msg' => $msg,
                'data' => $returnData,
                'extend' => $extend,
            );
        } else {
            $data = array(
                'code' => $code,
                'msg' => $msg,
                'data' => $returnData
            );
        }

        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit();
    }
}

if (!function_exists('numberToAbbr')) {
    /**
     * 缩写数字为k，w
     */
    function numberToAbbr($number)
    {
        if ($number < 1000) {
            return $number;
        }
        if ($number >= 1000 && $number < 10000) {
            return number_format($number / 1000, 2) . 'k';
        }
        return number_format($number / 10000, 2) . 'w';
    }
}

if (!function_exists('siteName')) {
    function siteName()
    {
        global $globalConfig;
        return isset($globalConfig['title']) && $globalConfig['title'] ? $globalConfig['title'] : '管理系统';
    }
}

if (!function_exists('siteLogo')) {
    function siteLogo()
    {
        global $globalConfig;
        return isset($globalConfig['logo']) && $globalConfig['logo'] ? $globalConfig['logo'] : '/static/admin/images/logo.png';
    }
}

if (!function_exists('letterAvatar')) {
    /**
     * 昵称生成首字头像
     * @param $nickname
     * @return string
     */
    function letterAvatar($nickname): string
    {
        $bg = "rgb(247,186,11)";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($nickname, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        // 确保图片保存的路径存在
        $tempPath = app()->getRootPath() . 'public' . DS . 'static' . DS . 'admin' . DS . 'images' . DS;
        $filename = md5('avatar_' . uniqid());
        // 生成图片链接
        $data = substr('data:image/svg+xml;base64,' . $src, strpos('data:image/svg+xml;base64,' . $src, ',') + 1);
        // 对数据进行Base64解码
        $fileData = base64_decode($data);
        // 创建输出目录如果它不存在
        if (!file_exists($tempPath)) {
            mkdir($tempPath, 0755, true);
        }
        // 将解码后的数据保存到文件
        $file = $tempPath . $filename . '.svg';
        if (file_put_contents($file, $fileData)) {
            // 返回图片的URL
            return '/static/admin/images/' . $filename . '.svg';
        }
        return '/static/admin/images/avatar.jpg';
    }
}

if (!function_exists('getIp')) {
    /**
     * 获取IP地址
     * @return mixed|string
     */
    function getIp()
    {
        $ip = false;
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) {
                array_unshift($ips, $ip);
                $ip = FALSE;
            }
            for ($i = 0; $i < count($ips); $i++) {
                if (!preg_match("^(10|172\.16|192\.168)\.", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        return ($ip ?: $_SERVER['REMOTE_ADDR']);
    }
}